package handlers

import (
	"context"
	"log"
	"net/http"
	"strconv"

	"gitee.com/gldmmhh/kiteclient/kitex_gen/bbs"
	"gitee.com/gldmmhh/kiteclient/kitex_gen/user"
	"github.com/gin-gonic/gin"
)

// GetUserPosts 查询用户发布的帖子数
func GetUserPosts(c *gin.Context) {
	userId, _ := strconv.ParseInt(c.Param("userId"), 10, 64)
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))

	// 打印日志
	log.Printf("GetUserPosts: userId=%d, page=%d, size=%d", userId, page, size)

	req := &bbs.GetUserPostsRequest{
		UserId: userId,
		Page:   int32(page),
		Size:   int32(size),
	}

	resp, err := PostClient.GetUserPosts(context.Background(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		log.Printf("error: %v", err)
		return
	}

	c.JSON(http.StatusOK, resp)
}

// GetUser 查询用户信息
func GetUser(c *gin.Context) {
	userId, _ := strconv.ParseInt(c.Param("userId"), 10, 64)

	// 打印日志
	log.Printf("GetUser: userId=%d", userId)

	req := &user.GetUserRequest{
		UserId: userId,
	}

	resp, err := UserClient.GetUser(context.Background(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, resp)
}

// GetUserFollowing 查询用户关注的用户列表
func GetUserFollowing(c *gin.Context) {
	userId, _ := strconv.ParseInt(c.Param("userId"), 10, 64)
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))

	// 打印日志
	log.Printf("GetUserFollowing: userId=%d, page=%d, size=%d", userId, page, size)

	req := &user.GetFollowingRequest{
		UserId: userId,
		Page:   int32(page),
		Size:   int32(size),
	}

	resp, err := UserClient.GetFollowing(context.Background(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, resp)
}

// FollowUser 关注用户
func FollowUser(c *gin.Context) {
	userId, _ := strconv.ParseInt(c.Param("userId"), 10, 64)

	var reqBody struct {
		FollowerId int64 `json:"followerId"`
	}
	if err := c.ShouldBindJSON(&reqBody); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	// 打印日志
	log.Printf("FollowUser: userId=%d, followerId=%d", userId, reqBody.FollowerId)

	req := &user.FollowUserRequest{
		UserId:     userId,
		FollowerId: reqBody.FollowerId,
	}

	resp, err := UserClient.FollowUser(context.Background(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if resp.Code == 200 {
		c.JSON(http.StatusCreated, resp)
	} else {
		c.JSON(http.StatusBadRequest, resp)
	}
}
